<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>H2 Database 事务隔离性实现原理 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="H2 Database 事务隔离性实现原理使用测试 cases: 12345678910111213隔离级别 RC    A 开启事务    B 开启事务    B 插入数据并提交    A 可以读取到隔离级别 RR    A 开启事务    B 开启事务    A 查询    B 插入数据并提交    A 读取不到    A 自己插入数据    A 可以读取到自己插入的数据  功能H2 支持的事">
<meta property="og:type" content="article">
<meta property="og:title" content="H2 Database 事务隔离性实现原理">
<meta property="og:url" content="https://flyingzc.github.io/articles/h2/h2database06-transaction-isolation.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="H2 Database 事务隔离性实现原理使用测试 cases: 12345678910111213隔离级别 RC    A 开启事务    B 开启事务    B 插入数据并提交    A 可以读取到隔离级别 RR    A 开启事务    B 开启事务    A 查询    B 插入数据并提交    A 读取不到    A 自己插入数据    A 可以读取到自己插入的数据  功能H2 支持的事">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2024-11-11T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.211Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="H2">
<meta property="article:tag" content="Database">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "H2 Database 事务隔离性实现原理",
  "url": "https://flyingzc.github.io/articles/h2/h2database06-transaction-isolation.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2024-11-11T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.211Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/h2/h2database06-transaction-isolation.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'H2 Database 事务隔离性实现原理',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">H2 Database 事务隔离性实现原理</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">H2 Database 事务隔离性实现原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-11-11T16:00:00.000Z" title="发表于 2024-11-12 00:00:00">2024-11-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.211Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/H2/">H2</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="H2-Database-事务隔离性实现原理"><a href="#H2-Database-事务隔离性实现原理" class="headerlink" title="H2 Database 事务隔离性实现原理"></a>H2 Database 事务隔离性实现原理</h1><h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>测试 cases:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs km">隔离级别 RC<br>    A 开启事务<br>    B 开启事务<br>    B 插入数据并提交<br>    A 可以读取到<br>隔离级别 RR<br>    A 开启事务<br>    B 开启事务<br>    A 查询<br>    B 插入数据并提交<br>    A 读取不到<br>    A 自己插入数据<br>    A 可以读取到自己插入的数据<br></code></pre></td></tr></table></figure>

<h2 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h2><p>H2 支持的事务隔离级别，定义在 IsolationLevel 里。<br>包括 READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SNAPSHOT, SERIALIZABLE。<br>其中 REPEATABLE_READ 不允许出现 脏读 和 不可重复读，但是允许出现幻读。<br>SNAPSHOT 不允许出现 脏读 和 不可重复读 和 幻读。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Level of isolation.</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title class_">IsolationLevel</span> &#123;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * Dirty reads, non-repeatable reads and phantom reads are allowed.</span><br><span class="hljs-comment">     */</span><br>    READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED, Constants.LOCK_MODE_OFF),<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * Dirty reads aren&#x27;t allowed; non-repeatable reads and phantom reads are</span><br><span class="hljs-comment">     * allowed.</span><br><span class="hljs-comment">     */</span><br>    READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED, Constants.LOCK_MODE_READ_COMMITTED),<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * Dirty reads and non-repeatable reads aren&#x27;t allowed; phantom reads are</span><br><span class="hljs-comment">     * allowed.</span><br><span class="hljs-comment">     */</span><br>    REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ, Constants.LOCK_MODE_TABLE),<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * Dirty reads, non-repeatable reads and phantom reads are&#x27;n allowed.</span><br><span class="hljs-comment">     */</span><br>    SNAPSHOT(Constants.TRANSACTION_SNAPSHOT, Constants.LOCK_MODE_TABLE),<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * Dirty reads, non-repeatable reads and phantom reads are&#x27;n allowed.</span><br><span class="hljs-comment">     * Concurrent and serial execution of transactions with this isolation level</span><br><span class="hljs-comment">     * should have the same effect.</span><br><span class="hljs-comment">     */</span><br>    SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE, Constants.LOCK_MODE_TABLE);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="类"><a href="#类" class="headerlink" title="类"></a>类</h2><h3 id="TMIterator"><a href="#TMIterator" class="headerlink" title="TMIterator"></a>TMIterator</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs km">TMIterator<br>    RepeatableIterator<br>    CommittedIterator<br>    UncommittedIterator<br></code></pre></td></tr></table></figure>

<h3 id="Snapshot"><a href="#Snapshot" class="headerlink" title="Snapshot"></a>Snapshot</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 快照.包含 map 的根节点引用 和 正在提交的事务集合.</span><br><span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Snapshot</span>&lt;K,V&gt; &#123;<br><br>    <span class="hljs-comment">/** </span><br><span class="hljs-comment">     * mvMap 根节点引用.</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">final</span> RootReference&lt;K,V&gt; root;<br><br>    <span class="hljs-comment">/** </span><br><span class="hljs-comment">     * 提交中的事务.对应创建快照当时的 TransactionStore.committingTransactions</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">final</span> BitSet committingTransactions;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="Transaction-TransactionMap"><a href="#Transaction-TransactionMap" class="headerlink" title="Transaction &amp; TransactionMap"></a>Transaction &amp; TransactionMap</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs km">一个物理连接对应一个 Transaction.<br>一个 mvMap 对应一个 TransactionMap.<br>一个 Transaction 对应多个 TransactionMap,因为一个事务可能涉及到多张表.<br></code></pre></td></tr></table></figure>

<h2 id="总体流程"><a href="#总体流程" class="headerlink" title="总体流程"></a>总体流程</h2><h3 id="创建物理连接"><a href="#创建物理连接" class="headerlink" title="创建物理连接"></a>创建物理连接</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs km">第一次获取 Transaction 对象时创建 Transaction<br>    原子性生成唯一的事务 id<br>    根据 undo log id(事务内从0开始,此时为0) 和 事务隔离级别创建 Transaction 对象。<br>        根据事务 id 创建 undo log mvMap。<br>        Transaction 包含 mvMap id -&gt; transaction map 的映射。此时为空，因为还未涉及到表操作。<br></code></pre></td></tr></table></figure>

<p>获取连接里的 databaseName,依次创建 Database -&gt; MVTable -&gt; MVPrimaryIndex -&gt; TransactionMap.<br>即一个连接的一个 MVPrimaryIndex 对应一个 TransactionMap.</p>
<p>TransactionMap 构成:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TransactionMap</span>&lt;K, V&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AbstractMap</span>&lt;K,V&gt; &#123;<br><br>    <span class="hljs-comment">/** </span><br><span class="hljs-comment">     * 用于写的 map</span><br><span class="hljs-comment">     * The map used for writing (the latest version).</span><br><span class="hljs-comment">     * &lt;p&gt;</span><br><span class="hljs-comment">     * Key: key the key of the data.</span><br><span class="hljs-comment">     * Value: &#123; transactionId, oldVersion, value &#125;</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> MVMap&lt;K, VersionedValue&lt;V&gt;&gt; map;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 当前 map 关联的事务</span><br><span class="hljs-comment">     * The transaction which is used for this map.</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Transaction transaction;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 根据隔离级别可能是事务开启时的快照，或者事务执行 statement 时候的快照.</span><br><span class="hljs-comment">     * </span><br><span class="hljs-comment">     * Snapshot of this map as of beginning of transaction or</span><br><span class="hljs-comment">     * first usage within transaction or</span><br><span class="hljs-comment">     * beginning of the statement, depending on isolation level</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> Snapshot&lt;K,VersionedValue&lt;V&gt;&gt; snapshot;<br><br>    <span class="hljs-comment">/** </span><br><span class="hljs-comment">     * 开始执行 statement 时候的快照.</span><br><span class="hljs-comment">     * </span><br><span class="hljs-comment">     * Snapshot of this map as of beginning of beginning of the statement</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> Snapshot&lt;K,VersionedValue&lt;V&gt;&gt; statementSnapshot;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * map数据是否被当前事务修改过</span><br><span class="hljs-comment">     * Indicates whether underlying map was modified from within related transaction</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-type">boolean</span> hasChanges;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> TxDecisionMaker&lt;K,V&gt; txDecisionMaker;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> TxDecisionMaker&lt;K,V&gt; ifAbsentDecisionMaker;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> TxDecisionMaker&lt;K,V&gt; lockDecisionMaker;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>一个 session 对应一个 Transaction,连接内第一次获取 Transaction 对象时,会创建 transaction 实例,并缓存到 SessionLocal 里.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">transaction = store.getTransactionStore().begin(<span class="hljs-built_in">this</span>, <span class="hljs-built_in">this</span>.lockTimeout, id, isolationLevel); <span class="hljs-comment">// 开启事务.传入 锁超时时间, session id, 隔离级别</span><br></code></pre></td></tr></table></figure>

<p>此时会原子性生成唯一的事务id.<br>根据 undo log id(事务内从0开始,此时为0) 和 事务隔离级别创建 Transaction 对象.<br>根据事务id创建 undo log mvMap.</p>
<p>Transaction 结构如下:<br>一个 Transaction 是会包含多个 TransactionMap,比如对应该事务内涉及的多张表,每张表的 mvMap 都会有对应的 TransactionMap.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Transaction</span> &#123;<br>   <br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_CLOSED</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_OPEN</span> <span class="hljs-operator">=</span> <span class="hljs-number">1</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_PREPARED</span> <span class="hljs-operator">=</span> <span class="hljs-number">2</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_COMMITTED</span> <span class="hljs-operator">=</span> <span class="hljs-number">3</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_ROLLING_BACK</span> <span class="hljs-operator">=</span> <span class="hljs-number">4</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_ROLLED_BACK</span>  <span class="hljs-operator">=</span> <span class="hljs-number">5</span>;<br><br>    <span class="hljs-comment">// 在事务中存储的“operation id”中有多少位属于日志id（其余的属于事务id）。</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">LOG_ID_BITS</span> <span class="hljs-operator">=</span> <span class="hljs-number">40</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">STATUS_BITS</span> <span class="hljs-operator">=</span> <span class="hljs-number">4</span>;<br><br>    <span class="hljs-keyword">final</span> TransactionStore store;<br>    <span class="hljs-keyword">final</span> TransactionStore.RollbackListener listener;<br><br>    <span class="hljs-comment">// 事务id</span><br>    <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> transactionId;<br><br>    <span class="hljs-comment">/* 事务状态是一个原子复合字段：1.创建事务时初始化;2.事务内操作会递增logId;2.事务提交/回滚时修改事务状态 status</span><br><span class="hljs-comment">     * Transaction state is an atomic composite field:</span><br><span class="hljs-comment">     * bit  45      : flag whether transaction had rollback(s) 位 45：标记事务是否有回滚</span><br><span class="hljs-comment">     * bits 44-41   : status 位 44-41：状态位</span><br><span class="hljs-comment">     * bits 40      : overflow control bit, 1 indicates overflow 40：溢出控制位，1 表示溢出</span><br><span class="hljs-comment">     * bits 39-0    : log id of the last entry in the undo log map 位 39-0：undo log 日志 map 中最后一个条目的日志 ID</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> AtomicLong statusAndLogId;<br><br>    <span class="hljs-keyword">private</span> MVStore.TxCounter txCounter;<br><br>    <span class="hljs-type">int</span> timeoutMillis;<br><br>    <span class="hljs-comment">// 创建当前事务的 session id</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> ownerId;<br><br>    <span class="hljs-comment">/** </span><br><span class="hljs-comment">     * mvMap id -&gt; transaction map.</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;Integer, TransactionMap&lt;?,?&gt;&gt; transactionMaps = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br><br>    <span class="hljs-keyword">final</span> IsolationLevel isolationLevel;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="开启事务"><a href="#开启事务" class="headerlink" title="开启事务"></a>开启事务</h3><p>设置 autoCommit 标记开启事务。</p>
<h3 id="插入-修改数据"><a href="#插入-修改数据" class="headerlink" title="插入&#x2F;修改数据"></a>插入&#x2F;修改数据</h3><p>事务内插入的数据是未提交状态，在事务提交操作时变更成已提交状态。</p>
<p>TransactionMap 重写了 Map 的 putIfAbsent 方法，进行事务性插入操作到 btree。<br>插入数据通过 TxDecisionMaker.PutIfAbsentDecisionMaker#decide 进行事务插入操作决定，会根据 当前值、目标值 和 游标位置 决定操作类型。<br>然后会调用 <code>TransactionMap#getFromSnapshot</code> 根据事务隔离级别读取对应的值。</p>
<h5 id="TransactionMap-getFromSnapshot"><a href="#TransactionMap-getFromSnapshot" class="headerlink" title="TransactionMap#getFromSnapshot"></a>TransactionMap#getFromSnapshot</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs km">对于 REPEATABLE_READ<br>    如果当前事务有数据变更<br>        获取 statement 级别快照,获取快照根节点,判断操作数据的事务id是否是当前事务,如果是返回当前值(读自己可见).<br>    如果当前事务没有数据变更<br>        获取事务级别快照 getSnapshot<br>        根据快照的根节点 和 创建快照时候的 committingTransactions 决定可见性<br>            获取当前数据对应的事务id<br>                操作当前数据的事务不是当前事务 &amp; 事务不在提交中<br>                    返回已提交的值 CommittedValue<br>                操作当前数据的事务是当前事务 或者 正在提交中<br>                    返回当前值 CurrentValue<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Get the value for the given key, or null if value does not exist in accordance with transactional rules.</span><br><span class="hljs-comment"> * Value is taken from a snapshot, appropriate for an isolation level of the related transaction</span><br><span class="hljs-comment"> *</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> key the key</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> the value, or null if not found</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> V <span class="hljs-title function_">getFromSnapshot</span><span class="hljs-params">(K key)</span> &#123;<br>    <span class="hljs-keyword">switch</span> (transaction.isolationLevel) &#123;<br>    <span class="hljs-keyword">case</span> READ_UNCOMMITTED: &#123; <span class="hljs-comment">// 直接从语句快照中获取值</span><br>        Snapshot&lt;K,VersionedValue&lt;V&gt;&gt; snapshot = getStatementSnapshot();<br>        VersionedValue&lt;V&gt; data = map.get(snapshot.root.root, key);<br>        <span class="hljs-keyword">if</span> (data != <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-keyword">return</span> data.getCurrentValue();<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>    <span class="hljs-keyword">case</span> REPEATABLE_READ:<br>    <span class="hljs-keyword">case</span> SNAPSHOT:<br>    <span class="hljs-keyword">case</span> SERIALIZABLE:<br>        <span class="hljs-keyword">if</span> (transaction.hasChanges()) &#123; <span class="hljs-comment">// RR 检查当前事务是否有更改.如果有更改，从语句快照中获取值</span><br>            Snapshot&lt;K,VersionedValue&lt;V&gt;&gt; snapshot = getStatementSnapshot();<br>            VersionedValue&lt;V&gt; data = map.get(snapshot.root.root, key);<br>            <span class="hljs-keyword">if</span> (data != <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-type">long</span> <span class="hljs-variable">id</span> <span class="hljs-operator">=</span> data.getOperationId();<br>                <span class="hljs-keyword">if</span> (id != <span class="hljs-number">0L</span> &amp;&amp; transaction.transactionId == TransactionStore.getTransactionId(id)) &#123;<br>                    <span class="hljs-keyword">return</span> data.getCurrentValue();<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-comment">//$FALL-THROUGH$</span><br>    <span class="hljs-keyword">case</span> READ_COMMITTED:<br>    <span class="hljs-keyword">default</span>:<br>        Snapshot&lt;K,VersionedValue&lt;V&gt;&gt; snapshot = getSnapshot(); <span class="hljs-comment">// 获取 snapshot</span><br>        <span class="hljs-keyword">return</span> getFromSnapshot(snapshot.root, snapshot.committingTransactions, key); <span class="hljs-comment">// 获取 snapshot 中的数据</span><br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">private</span> V <span class="hljs-title function_">getFromSnapshot</span><span class="hljs-params">(RootReference&lt;K, VersionedValue&lt;V&gt;&gt; rootRef, BitSet committingTransactions, K key)</span> &#123;<br>        VersionedValue&lt;V&gt; data = map.get(rootRef.root, key);<br>    <span class="hljs-keyword">if</span> (data == <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-comment">// doesn&#x27;t exist</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>    <span class="hljs-type">long</span> <span class="hljs-variable">id</span> <span class="hljs-operator">=</span> data.getOperationId(); <span class="hljs-comment">// 获取操作 id</span><br>    <span class="hljs-keyword">if</span> (id != <span class="hljs-number">0</span>) &#123; <span class="hljs-comment">// 如果操作 id 不为 0</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">tx</span> <span class="hljs-operator">=</span> TransactionStore.getTransactionId(id); <span class="hljs-comment">// 获取事务 id</span><br>        <span class="hljs-keyword">if</span> (tx != transaction.transactionId &amp;&amp; !committingTransactions.get(tx)) &#123; <span class="hljs-comment">// 如果事务 id 不等于当前事务 id 并且 committingTransactions 不包含这个事务(不是当前事务&amp;事务未提交)</span><br>            <span class="hljs-comment">// added/modified/removed by uncommitted transaction, change should not be visible</span><br>            <span class="hljs-keyword">return</span> data.getCommittedValue(); <span class="hljs-comment">// 返回已提交的值</span><br>        &#125;<br>    &#125;<br>    <span class="hljs-comment">// added/modified/removed by this transaction or another transaction which is committed by now</span><br>    <span class="hljs-keyword">return</span> data.getCurrentValue(); <span class="hljs-comment">// (当前事务 或 已提交事务),返回当前值</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="提交事务"><a href="#提交事务" class="headerlink" title="提交事务"></a>提交事务</h3><p>CommitDecisionMaker</p>
<p>org.h2.mvstore.tx.CommitDecisionMaker#selectValue<br>获取 VersionedValueUncommitted 里的 DefaultRow 返回(VersionedValue)。<br>执行 btree 更新操作，<code>p.setValue(index, value);</code> 将 VersionedValueUncommitted 替换成了 DefaultRow。</p>
<h3 id="回滚事务"><a href="#回滚事务" class="headerlink" title="回滚事务"></a>回滚事务</h3><h3 id="查询数据"><a href="#查询数据" class="headerlink" title="查询数据"></a>查询数据</h3><p>查询数据时会获取当前 SQL 里涉及到的所有表，清理当前事务对象里缓存的这些表对应的缓存(清理 transactionMaps)。<br>然后遍历这些表，根据 mvMap 的根节点和 committingTransactions 创建语句级别快照 statement snapshot。<br>通过 snapshot 和不同的隔离级别创建数据迭代器。最终决定数据的可见性。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs km">1.创建快照<br>    startStatementWithinTransaction<br>        获取依赖的表 dependencies mvTables<br>        对于 REPEATABLE_READ 级别<br>            添加表对应的 mvMap 到 `HashSet&lt;MVMap&lt;Object,VersionedValue&lt;Object&gt;&gt;&gt; maps` 里(MVPrimaryIndex-&gt;transactionMap-&gt;versionedValueMap)<br>    markStatementStart<br>        markStatementEnd<br>            遍历 transactionMaps(每张表对应一个 transactionMap),清理每个 transactionMap 对应的 snapshot(后面重新创建)<br>        通过每个 MVMap&lt;Object,VersionedValue&lt;Object&gt;&gt; map 获取 or 创建对应的 transactionMap<br>            创建 decision maker<br>            根据不同隔离级别,允许不可重复读 ? lock : repeatable read lock<br>        为每个 mvMap 创建 snapshot 快照,设置到对应的 transactionMap 里,传入 committingTransactions<br>2.迭代器迭代数据<br>    对于 RR 和以上隔离级别，当前事务没有变更数据，创建 CommittedIterator。<br>    否则根据隔离级别创建对应的迭代器。<br>    通过 transactionMap.snapshot 快照的根节点创建 cursor<br>    根据快照迭代数据<br>3.执行完毕查询清理快照<br>    session.endStatement()<br>        transaction.markStatementEnd()<br>        遍历 transactionMaps,清空 statementSnapshot<br></code></pre></td></tr></table></figure>

<h4 id="1-创建快照"><a href="#1-创建快照" class="headerlink" title="1.创建快照"></a>1.创建快照</h4><p>获取查询涉及的所有表，根据表对应的 mvMap 创建对应的 transactionMap。<br>根据 transactionMap 的当前 root 节点 和 committingTransactions，创建对应的语句级别快照 statement snapshot。<br>事务内第一次创建 statement snapshot, 会将 statement snapshot 设置给事务级别快照 snapshot。<br>根据不同隔离级别创建对应的迭代器 TMIterator 的具体实现。<br>    对于 REPEATABLE_READ 及其以上隔离级别的事务<br>        如果当前事务有数据修改，创建 RepeatableIterator，否则创建 CommittedIterator<br>    READ_COMMITTED 隔离级别事务创建 CommittedIterator<br>    READ_UNCOMMITTED 隔离级别事务创建 UncommittedIterator</p>
<h4 id="2-迭代器迭代数据"><a href="#2-迭代器迭代数据" class="headerlink" title="2.迭代器迭代数据"></a>2.迭代器迭代数据</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 创建迭代器</span><br>TMIterator(TransactionMap&lt;K, V&gt; transactionMap, K from, K to, Snapshot&lt;K, VersionedValue&lt;V&gt;&gt; snapshot,<br>                <span class="hljs-type">boolean</span> reverse, <span class="hljs-type">boolean</span> forEntries) &#123; <span class="hljs-comment">// 创建迭代器</span><br>            <span class="hljs-type">Transaction</span> <span class="hljs-variable">transaction</span> <span class="hljs-operator">=</span> transactionMap.getTransaction();<br>    <span class="hljs-built_in">this</span>.transactionId = transaction.transactionId;<br>    <span class="hljs-built_in">this</span>.forEntries = forEntries;<br>    <span class="hljs-built_in">this</span>.cursor = transactionMap.map.cursor(snapshot.root, from, to, reverse); <span class="hljs-comment">// 通过快照的根节点创建 cursor</span><br>    <span class="hljs-built_in">this</span>.committingTransactions = snapshot.committingTransactions;<br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="不同隔离级别迭代器实现类"><a href="#不同隔离级别迭代器实现类" class="headerlink" title="不同隔离级别迭代器实现类"></a>不同隔离级别迭代器实现类</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs km">TMIterator<br>    RepeatableIterator<br>        适用于 REPEATABLE_READ 及其以上隔离级别的事务<br>    CommittedIterator<br>        适用于 READ_COMMITTED 隔离级别的事务<br>    UncommittedIterator<br>        适用于 READ_UNCOMMITTED 隔离级别事务<br></code></pre></td></tr></table></figure>

<h6 id="1-RepeatableIterator"><a href="#1-RepeatableIterator" class="headerlink" title="1.RepeatableIterator"></a>1.RepeatableIterator</h6><p>适用于 REPEATABLE_READ 及其以上隔离级别的事务的迭代器。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs km">构造方法<br>    通过事务级别快照创建 cursor<br>    通过语句级别快照创建 uncommittedCursor，用于迭代当前事务没有提交的事务<br>fetchNext 迭代数据<br>    先从事务级别 snapshot 的 cursor 迭代 next 数据<br>        如果有数据判断可见性<br>            若事务ID等于当前事务ID 或 事务正在提交,获取当前值 current value<br>            否则使用 committed value<br>    再从语句级别快照(statement snapshot) 的 uncommittedCursor 里迭代数据<br>        如果有数据判断可见性<br>            若操作数据的事务ID等于当前事务ID,获取当前值 current value<br>            否则使用 committed value<br>    然后对比决定返回 snapshot 还是 uncommitted 值<br></code></pre></td></tr></table></figure>

<h6 id="2-CommittedIterator"><a href="#2-CommittedIterator" class="headerlink" title="2.CommittedIterator"></a>2.CommittedIterator</h6><p>适用于 READ_COMMITTED 隔离级别的事务的迭代器。<br>高于 READ_COMMITTED 隔离级别的事务如果自身没有修改过数据，也可以使用。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs km">构造方法<br>    使用事务级别快照创建 cursor<br>fetchNext 迭代数据<br>    从 cursor 里获取下一行数据<br>    获取数据 operation id 里的 transaction id<br>    如果操作当前行数据是 其他事务尚未提交的操作<br>        判断条件: transaction id 不是当前事务 并且 不在提交列表里<br>    则获取已提交的值(committed value)<br>    否则获取当前值(current value)<br></code></pre></td></tr></table></figure>

<h6 id="3-UncommittedIterator"><a href="#3-UncommittedIterator" class="headerlink" title="3.UncommittedIterator"></a>3.UncommittedIterator</h6><p>适用于 READ_UNCOMMITTED 隔离级别事务的迭代器。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs km">构造方法<br>    每次创建新的快照 snapshot,创建迭代器<br>fetchNext 迭代数据<br>    从 cursor 里获取下一行数据<br>    每次都获取当前值 current value<br></code></pre></td></tr></table></figure>

<h4 id="3-执行完毕查询清理快照"><a href="#3-执行完毕查询清理快照" class="headerlink" title="3.执行完毕查询清理快照"></a>3.执行完毕查询清理快照</h4><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/h2/h2database06-transaction-isolation.html">https://flyingzc.github.io/articles/h2/h2database06-transaction-isolation.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/H2/">H2</a><a class="post-meta__tags" href="/tags/Database/">Database</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/h2/h2database01-build.html" title="H2 Database IDEA 环境搭建"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-08-20</div><div class="info-item-2">H2 Database IDEA 环境搭建</div></div><div class="info-2"><div class="info-item-1">H2 Database IDEA 源码 DEBUG 环境搭建基于最新的 version-2.3.230 拉取分支。 123git remote add h2 https://github.com/h2database/h2database.git git fetch h2git checkout -b version-2.3.230 version-2.3.230  使用12345# 启动java -jar h2*.jar# H2 shell 方式使用java -cp h2-*.jar org.h2.tools.Shell  h2 shell启动类 org.h2.tools.Shell 12# 配置启动参数-url &quot;jdbc:h2:~/test&quot; -user &quot;sa&quot; -password &quot;&quot;   测试 casecreate table + insert 1234567891011121314151617181920212223242526272829303132333435363738394041Welcome...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database02-mvstore-init.html" title="H2 Database MVStore 初始化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-08-20</div><div class="info-item-2">H2 Database MVStore 初始化</div></div><div class="info-2"><div class="info-item-1">H2 Database MVStore 初始化作用MVStore（multi-version store）：H2 的默认存储子系统，支持多版本，持久化的、日志结构 的 键值存储。 功能123456789101112Maps    每个 store 包含多个 mvMaps,可以通过 java.util.Map 接口访问Versions    支持多版本Transactions    支持事务(并发事务&amp;两阶段提交)Concurrent Operations and Caching    支持并发读写Log Structured Storage    日志结构化存储支持文件存储和内存操作支持可插拔  文件存储格式12345# 文件存储格式[ file header 1 ] [ file header 2 ] [ chunk ] [ chunk ] ... [ chunk ]# chunk 存储格式[ header ] [ page ] [ page ] ... [ page ] [ footer ]  12345结构    File Header 文件头    Chunk...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database03-mvstore-commit.html" title="H2 Database MVStore Commit 流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-10-15</div><div class="info-item-2">H2 Database MVStore Commit 流程</div></div><div class="info-2"><div class="info-item-1">H2 Database MVStore Commit 流程作用BackgroundWriterThread 按照固定频率，将内存里修改的尚未保存的 Page 信息持久化到存储。 流程启动阶段创建后台线程org.h2.mvstore.MVStore#setAutoCommitDelay1.创建 BackgroundWriterThread 后台线程2.创建序列化线程 serializationExecutor3.创建持久化线程 bufferSaveExecutor设置自动提交更改的最大延迟（单位毫秒）。  默认值为 1000，这意味着所有更改最多在一秒后提交。  要禁用自动提交，需要将值设置为 0。在这种情况下，仅在显式调用 commit 时才会提交更改。 BackgroundWriterThread 线程逻辑定时任务周期性执行,比对内存里的 MVMap...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database06-transaction-commit.html" title="H2 Database 事务 Commit 流程实现原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-09-28</div><div class="info-item-2">H2 Database 事务 Commit 流程实现原理</div></div><div class="info-2"><div class="info-item-1">H2 Database 事务 Commit 流程实现原理使用测试 Demo: 123begin;insert into test values(1);commit;  功能模块类总体流程1234567891011121314解析 commit 语句执行 commit 语句    设置事务状态为已提交    根据 undoLogId 判断事务是否有更改操作,有更改继续提交    CAS 设置当前事务状态为已提交到 committingTransactions    遍历 undoLog mvMap        追加标记 undoLog 已提交到 undoLog mvMap 上        获取当前 undoLog 操作涉及的 mvMap id            遍历到对应 Page 的对应 index            将 VersionedValueUncommitted 类型更新成 DefaultRow 类型事务清理操作    清理 undoLog mvMap(更新 root 节点为 empty)    清理事务状态    释放 table...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database05-page.html" title="H2 Database MvMap 插入数据流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-10-12</div><div class="info-item-2">H2 Database MvMap 插入数据流程</div></div><div class="info-2"><div class="info-item-1">H2 Database MvMap 插入数据流程H2Database 使用 MVStore 作为默认的存储子系统，支持多版本，持久化的键值存储。其中每一个 MVMap 对象代表了一颗 btree。MVMap 里包含了 btree 根页面的引用，这颗 btree 可以表示一张表、一个索引，或者用来记录 undo log 等。 使用12345678// 1.根据数据库文件名称打开 mvStoreMVStore s = MVStore.open(fileName);// 2.指定名称创建 mvMapMVMap&lt;Integer, String&gt; map = s.openMap(&quot;data&quot;);// 3.将数据插入到 mvMap 上for (int i = 0; i &lt; 400; i++) &#123;    map.put(i, &quot;Hello-&quot; + i);&#125;  相关类MVMap 类成员变量包含了 MVMap 这个 btree 的唯一 id，btree 的根节点引用。btree 每个节点上存储的 key、value...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database06-transaction-rollback.html" title="H2 Database 事务 Rollback 流程实现原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-10-16</div><div class="info-item-2">H2 Database 事务 Rollback 流程实现原理</div></div><div class="info-2"><div class="info-item-1">H2 Database 事务 Rollback 流程实现原理使用1234567Connection conn = getConnection();// 开启事务conn.setAutoCommit(false);// 执行 SQLexecuteWithLog(conn, &quot;insert into Test(id, name) values(1, &#x27;name1&#x27;), (2, &#x27;name2&#x27;)&quot;);// 回滚事务conn.rollback();  功能模块类总体流程当执行事务回滚时，会获取当前事务所有的 undoLogId，然后从后向前遍历每一个 undoLogId。对于每一个 undoLogId，先遍历 undoLog btree 找到存储的 Record。Record 信息里包含了当前 undoLogId 操作的数据行信息。然后根据 Record 信息找到对应记录的 primary key btree，根据主键 id 找到对应行记录进行回滚操作。当记录回滚完之后，再回滚 undoLog btree 上的 undoLog...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#H2-Database-%E4%BA%8B%E5%8A%A1%E9%9A%94%E7%A6%BB%E6%80%A7%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">H2 Database 事务隔离性实现原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">1.1.</span> <span class="toc-text">使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8A%9F%E8%83%BD"><span class="toc-number">1.2.</span> <span class="toc-text">功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB"><span class="toc-number">1.3.</span> <span class="toc-text">类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#TMIterator"><span class="toc-number">1.3.1.</span> <span class="toc-text">TMIterator</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Snapshot"><span class="toc-number">1.3.2.</span> <span class="toc-text">Snapshot</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Transaction-TransactionMap"><span class="toc-number">1.3.3.</span> <span class="toc-text">Transaction &amp; TransactionMap</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-number">1.4.</span> <span class="toc-text">总体流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E7%89%A9%E7%90%86%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.4.1.</span> <span class="toc-text">创建物理连接</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%80%E5%90%AF%E4%BA%8B%E5%8A%A1"><span class="toc-number">1.4.2.</span> <span class="toc-text">开启事务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%92%E5%85%A5-%E4%BF%AE%E6%94%B9%E6%95%B0%E6%8D%AE"><span class="toc-number">1.4.3.</span> <span class="toc-text">插入&#x2F;修改数据</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#TransactionMap-getFromSnapshot"><span class="toc-number">1.4.3.0.1.</span> <span class="toc-text">TransactionMap#getFromSnapshot</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%90%E4%BA%A4%E4%BA%8B%E5%8A%A1"><span class="toc-number">1.4.4.</span> <span class="toc-text">提交事务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E6%BB%9A%E4%BA%8B%E5%8A%A1"><span class="toc-number">1.4.5.</span> <span class="toc-text">回滚事务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E6%95%B0%E6%8D%AE"><span class="toc-number">1.4.6.</span> <span class="toc-text">查询数据</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E5%88%9B%E5%BB%BA%E5%BF%AB%E7%85%A7"><span class="toc-number">1.4.6.1.</span> <span class="toc-text">1.创建快照</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E8%BF%AD%E4%BB%A3%E5%99%A8%E8%BF%AD%E4%BB%A3%E6%95%B0%E6%8D%AE"><span class="toc-number">1.4.6.2.</span> <span class="toc-text">2.迭代器迭代数据</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%B8%8D%E5%90%8C%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-number">1.4.6.2.1.</span> <span class="toc-text">不同隔离级别迭代器实现类</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#1-RepeatableIterator"><span class="toc-number">1.4.6.2.1.1.</span> <span class="toc-text">1.RepeatableIterator</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#2-CommittedIterator"><span class="toc-number">1.4.6.2.1.2.</span> <span class="toc-text">2.CommittedIterator</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-UncommittedIterator"><span class="toc-number">1.4.6.2.1.3.</span> <span class="toc-text">3.UncommittedIterator</span></a></li></ol></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E6%89%A7%E8%A1%8C%E5%AE%8C%E6%AF%95%E6%9F%A5%E8%AF%A2%E6%B8%85%E7%90%86%E5%BF%AB%E7%85%A7"><span class="toc-number">1.4.6.3.</span> <span class="toc-text">3.执行完毕查询清理快照</span></a></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>